package com.fs.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.mapper.UserAddrMapper;
import com.fs.pojo.UserAddr;
import com.fs.vo.PageResult;
import com.fs.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class UserAddrServiceImpl implements UserAddrService {
    @Autowired
    private UserAddrMapper userAddrMapper;

    @Transactional
    @Override
    public SysResult add(UserAddr entity) {
        if(entity==null)return SysResult.fail();
        if(entity.getUserId()==null)return SysResult.fail("用户参数有误");
        if(entity.getUsername()==null) return SysResult.fail("收货人不能为空");
        if(entity.getPhone()==null)return SysResult.fail("联系方式不能为空");
        if(entity.getAddr()==null)return SysResult.fail("详细地址不能为空");
        if(entity.getProvice()==null || entity.getCity()==null || entity.getZone()==null){
            return SysResult.fail("请选择省市区");
        }

        //如果选择默认，则将其他的地址默认字段改成false
        if(entity.getDefaultAddr()){
            UserAddr entity1 = new UserAddr();
            entity1.setDefaultAddr(false);
            QueryWrapper<UserAddr> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",entity.getUserId());
            userAddrMapper.update(entity1,queryWrapper);
        }

        //地址标签

        //日期
        Date date = new Date();
        entity.setCreated(date)
                .setUpdated(date);
        int i = userAddrMapper.insert(entity);
        if(i>0){
            return SysResult.success();
        }

        return SysResult.fail("添加失败");
    }

    @Transactional
    @Override
    public SysResult edit(UserAddr entity) {
        int i = userAddrMapper.updateById(entity);
        return SysResult.success();
    }

    @Override
    @Transactional
    public SysResult list(PageResult request) {
        if(request==null)return SysResult.fail();

        int pageNum = request.getPageNum();
        int pageSize = request.getPageSize();

        if(pageNum<1)pageNum=1;
        if(pageSize<1)pageNum=10;

        Page<UserAddr> page = new Page<>(pageNum, pageSize);


        QueryWrapper<UserAddr> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(request.getQuery()),"username",request.getQuery())
                .orderByDesc("id");
        page=userAddrMapper.selectPage(page,queryWrapper);
        request.setTotal(page.getTotal()).setRows(page.getRecords());

        return SysResult.success(request);
    }

    @Override
    @Transactional
    public SysResult delById(Integer id) {
        userAddrMapper.deleteById(id);
        return SysResult.success();
    }
}
